'use strict';

const { Controller } = require('egg');

class UserController extends Controller {
  async login() {
    const { ctx, app } = this;
    const { tel, pwd } = ctx.request.body;
    // 查询数据库中是否存在该用户
    // eslint-disable-next-line no-undef
    const userResult = await app.mysql.get('user', { tel, pwd });
    if (userResult) {
      // 登录成功
      ctx.body = {
        success: true,
        message: '登录成功',
        // 返回用户头像信息
        avatar: userResult.avatar,
      };
    } else {
      // 登录失败
      ctx.body = {
        success: false,
        message: '用户名或密码错误',
      };
    }
  }

  async getInfo() {
    const { ctx, app } = this;
    const { uname, tel, email, avatar, pwd } = ctx.request.body;


    // 将表单数据插入到数据库中
    const inforesult = await app.mysql.insert('user', {
      tel,
      uname,
      email,
      avatar,
      pwd,
    });

    // 假设处理成功
    if (inforesult) {
      ctx.status = 200;
      ctx.body = {
        data: 200,
        message: '用户信息更新成功!',
      };
    } else {
      // 条件不满足时返回错误信息
      ctx.status = 400;
      ctx.body = {
        data: 400,
        message: '表单数据不完整',
      };
    }
  }
  async register() {
    const { ctx, app } = this;
    const { uname, tel, pwd, avatar } = ctx.request.body;

    // 判断手机号是否已经被注册
    const user = await app.mysql.get('user', { tel });
    if (user) {
      ctx.body = { success: false, message: '该手机号已经被注册' };
      return;
    }

    // 添加用户
    const result = await app.mysql.insert('user', { uname, tel, pwd, avatar });
    if (result.affectedRows === 1) {
      ctx.body = { success: true, message: '注册成功' };
    } else {
      ctx.body = { success: false, message: '注册失败' };
    }
  }

}

module.exports = UserController;
